import { DataTableColumns, NButton, NSpace, NSwitch, NTag, useMessage } from 'naive-ui'
import { useI18n } from 'vue-i18n'

import { deleteMenu, updateMenuStatus } from '@/apis'
import { MenuItem } from '@/apis/menu/type/vo'
import CustomPopconfirm from '@/components/CustomPopconfirm.vue'
import { StatusEnum } from '@/types/enum'
import { menuMap } from '@/types/map'
import { catchToTuple } from '@/utils'

export function useTable({ modalShow, modalType, modalFormData, init }: any) {
  const { t } = useI18n()
  const message = useMessage()

  // 加载中
  const loading = ref<boolean>(false)

  // 展开行
  const expandedRowKeys = ref<Array<string | number>>([])

  // 生成 columns 配置
  const columns = computed(
    (): DataTableColumns<MenuItem> => [
      {
        title: 'id',
        key: 'id',
      },
      {
        title: t('menus.name'),
        key: 'name',
        ellipsis: {
          tooltip: true,
        },
      },
      {
        title: t('menus.icon'),
        key: 'icon',
        ellipsis: {
          tooltip: true,
        },
        render: (row: MenuItem) => row.icon || '--',
      },
      {
        title: t('menus.permission'),
        key: 'permission',
        ellipsis: {
          tooltip: true,
        },
        render: (row: MenuItem) => row.permission || '--',
      },
      {
        title: t('menus.path'),
        key: 'path',
        ellipsis: {
          tooltip: true,
        },
        render: (row: MenuItem) => row.path || '--',
      },
      {
        title: t('common.sort'),
        key: 'sort',
        ellipsis: {
          tooltip: true,
        },
        render: (row: MenuItem) => row.sort || '--',
      },
      {
        title: t('menus.comp_type'),
        key: 'comp_type',
        ellipsis: {
          tooltip: true,
        },
        render(row: MenuItem) {
          if (row.comp_type === null) return '--'
          const config = menuMap[row.comp_type]
          return <NTag type={config.type}>{t(config.text)}</NTag>
        },
      },
      {
        title: t('common.status'),
        key: 'status',
        render(row: MenuItem) {
          return (
            <NSwitch
              checked-value={StatusEnum.DYNAMIC}
              unchecked-value={StatusEnum.STATIC}
              value={row.status}
              onUpdateValue={(status: StatusEnum) => changStatus({ row, status })}
            />
          )
        },
      },
      {
        title: t('common.create_time'),
        key: 'create_time',
        ellipsis: {
          tooltip: true,
        },
      },
      {
        title: t('common.update_time'),
        key: 'update_time',
        ellipsis: {
          tooltip: true,
        },
      },
      {
        title: t('common.action'),
        key: 'actions',
        width: 200,
        render(row: MenuItem) {
          return (
            <NSpace>
              <NButton type="info" size="small" text onClick={() => handleCreateMenu(row)}>
                {t('common.create')}
              </NButton>
              <NButton type="info" size="small" text onClick={() => handleEditMenu(row)}>
                {t('common.edit')}
              </NButton>
              <CustomPopconfirm
                buttonType="error"
                gradientType="error"
                btnName={t('common.delete')}
                msg={t('common.deleteConfirm')}
                onHandle-submit={() => handleDeleteMenu(row.id)}
              />
            </NSpace>
          )
        },
      },
    ],
  )

  // 生成 列表项 options 配置
  const checkboxOptions = computed(() =>
    columns.value.reduce<{ label: string; value: string }[]>((acc, column) => {
      if (column.type === 'selection') {
        acc.push({ label: t('common.selection'), value: 'selection' })
      }
      if ('title' in column && 'key' in column && typeof column.title === 'string' && typeof column.key === 'string') {
        if (column.key === 'actions') {
          acc.push({ label: t('common.action'), value: 'actions' })
        } else {
          acc.push({ label: column.title, value: column.key })
        }
      }
      return acc
    }, []),
  )

  // 当前选中项
  const checkedColumnsKeys = ref<string[]>(checkboxOptions.value.map((item) => item.value))

  // 根据当前选中项过滤出显示的列
  const filteredColumns = computed(() => {
    return columns.value.filter((column) => {
      if (checkedColumnsKeys.value.includes('selection') && column.type === 'selection') return column
      if ('key' in column && typeof column.key === 'string') return checkedColumnsKeys.value.includes(column.key)
      return false
    })
  })

  const handleCreateMenu = (row: MenuItem) => {
    modalShow.value = true
    modalType.value = 'create'
    modalFormData.value.parent_id = row.id
  }
  const handleEditMenu = (row: MenuItem) => {
    modalShow.value = true
    modalType.value = 'update'
    Object.assign(modalFormData.value, row)
  }
  const handleDeleteMenu = async (id: number) => {
    const [err, data] = await catchToTuple(deleteMenu({ id }))
    if (err) return
    if (data?.code === 200) {
      message.success(data.message)
      init()
    }
  }

  const handleCreate = () => {
    modalShow.value = true
    modalType.value = 'create'
  }
  // 切换状态
  const changStatus = async ({ row, status }: { row: MenuItem; status: StatusEnum }) => {
    row.status = status
    const [err, data] = await catchToTuple(updateMenuStatus({ id: row.id, status }))
    if (err) return

    if (data?.code !== 200) {
      row.status = status === StatusEnum.DYNAMIC ? StatusEnum.STATIC : StatusEnum.DYNAMIC
    }

    if (data?.code === 200) {
      message.success(data.message)
    }
  }

  return {
    loading,
    checkboxOptions,
    checkedColumnsKeys,
    filteredColumns,
    expandedRowKeys,
    handleCreate,
  }
}
